import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import ru.ksu.ktk.diploma.sdi.analyzer.contingency.NominalData;

public class FileUtil {
    private FileUtil() {
    }

    /**
     * read string values from file line by line
     * 
     * @param filePath
     * @return
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static List<String> readValues(String filePath) throws FileNotFoundException, IOException {
        List<String> values = new ArrayList<String>();

        InputStream inputStream = new FileInputStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String value;
        while ((value = reader.readLine()) != null){
            values.add(value);
        }
        reader.close();
        inputStream.close();

        return values;
    }

    /**
     * write string values into file line by line
     * 
     * @param values
     * @param filePath
     * @throws IOException
     */
    public static void write(List<String> values, String filePath) throws IOException {
        FileWriter fw = new FileWriter(filePath);

        for (String str : values){
            fw.write(str);
            fw.write("\n");
        }
        fw.flush();
        fw.close();
    }

    public static void writeNominalData(List<NominalData> nominalDataList, String filePath) throws IOException {
        FileWriter fw = new FileWriter(filePath);

        for (NominalData nominal : nominalDataList){
            String firstNominalValue = nominal.getFirstNominalValue();
            String secondNominalValue = nominal.getSecondNominalValue();
            int count = nominal.getCount();
            String str = String.format("%s %s %d", firstNominalValue, secondNominalValue, count);
            fw.write(str);
            fw.write("\n");
        }
        fw.flush();
        fw.close();

    }

    public static List<NominalData> readNominalData(String filePath) throws NumberFormatException, IOException {
        List<NominalData> nominalData = new ArrayList<NominalData>();
        InputStream inputStream = new FileInputStream(filePath);
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        String value;
        while ((value = reader.readLine()) != null){
            StringTokenizer st = new StringTokenizer(value, " ");
            String firstValue = st.nextToken().trim();
            String secondValue = st.nextToken().trim();
            int count = Integer.parseInt(st.nextToken());
            nominalData.add(new NominalData(firstValue, secondValue, count));
        }
        reader.close();
        inputStream.close();

        return nominalData;
    }
}
